package com.glorystone.ins.controller;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.ValidationException;

import com.glorystone.ins.domain.SysUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.common.common.Pageable;
import com.glorystone.ins.common.exception.ServiceException;
import com.glorystone.ins.domain.Dictionary;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.IDictionaryService;

/**
 * 基础封装
 */
public class BaseController {

    private static final Logger log = LoggerFactory.getLogger(BaseController.class);

    public enum RoleTypeIdEnum {
        BUSSNESSAll(2),BUSSNESS1(8), BUSSNESS2(9), BUSSNESS3(10),//2业务部 8业务员 9业务经理 10业务部负责人
        RISK1(11), RISK2(12), RISK3(13),RISK4(14),//风控部 11初审员 12终审员 13复核员 14风控部负责人
        FINANCE1(15), FINANCE2(16), FINANCE3(17);//财务部 15财务人员 16财务经理 17财务部负责人
        //ACCOUNT1(19), ACCOUNT2(20), ACCOUNT3(21);//结算部 19结算人员 20结算经理 21结算部负责人
        private Long value;
        RoleTypeIdEnum(int value) {
            this.value = Long.valueOf(value);
        }
        public Long getValue() {
            return value;
        }
    }

    @Autowired
    private IDictionaryService dictionaryService;

    public List<Dictionary> getDictionaryListByType(String type) {
    	List<Dictionary> list=dictionaryService.getDictionaryListByType(type);
    	return list;
    }
    
    /**
     * 表格数据加载请求：封裝表格(dataTable)的ajax请求參數
     *
     */
    public static PageVo parametToPageVo(HttpServletRequest request,Class<?> sc) {
        PageVo vo = new PageVo();

        //获取私有屬性
        Field[] fieldArray = sc.getDeclaredFields();

        // 封装查询参数
        Map<String, Object> parameters = new HashMap<>(10);
        for(Field field : fieldArray){
            String filedName = field.getName();
            String searchParameter = request.getParameter(filedName);
            if(!StringUtils.isEmpty(searchParameter)){
                log.info("查询参数=>filedName："+filedName+"--->"+"searchParameter:"+searchParameter);
                parameters.put(filedName,searchParameter);
            }
        }
        vo.setParameters(parameters);

        // 封装分页参数
        Pageable pageable = new Pageable();
        String start = request.getParameter("start");
        String length = request.getParameter("length");
        
        //封装排序参数
        String order = request.getParameter("order[0][column]");//排序的列号  
        String orderDir = request.getParameter("order[0][dir]");//排序的顺序asc or desc  
        String orderColumn = request.getParameter("columns["+order+"][data]");//排序的列
        log.info("标题排序参数：排序的列号："+order+"；排序的顺序："+orderDir+";排序的列："+orderColumn);
        Map<String, Object>  sortParameters=new HashMap<String, Object>();
        sortParameters.put("orderColumn", orderColumn);
        sortParameters.put("orderDir", orderDir);
        vo.setSort(sortParameters);
        
        pageable.setCurrentPage((Integer.parseInt(start)/Integer.parseInt(length)+1));
        log.info("分页参数=>第X页："+(Integer.parseInt(start)/Integer.parseInt(length)+1));
        //liuhongjie add by 2018/03/19 DataTable的aLengthMenu属性设置每页显示条数参数放入pagesize
        pageable.setPageSize(Integer.parseInt(length));
        vo.setPageable(pageable);

        return vo;
    }

    /**
     * 表格数据加载请求：封裝表格(dataTable)的ajax请求參數
     *
     */
    public static PageVo parametToPageVoData(HttpServletRequest request, Class<?> sc, SysUser user) {
        PageVo vo = new PageVo();

        //获取私有屬性
        Field[] fieldArray = sc.getDeclaredFields();

        // 封装查询参数
        Map<String, Object> parameters = new HashMap<>(10);
        for(Field field : fieldArray){
            String filedName = field.getName();
            String searchParameter = request.getParameter(filedName);
            if(!StringUtils.isEmpty(searchParameter)){
                log.info("查询参数=>filedName："+filedName+"--->"+"searchParameter:"+searchParameter);
                parameters.put(filedName,searchParameter);
            }
        }
        parameters.put("userType",user.getType());//0 内部用户 1外部用户
        parameters.put("level",user.getUserLevel());//1管理员级别 2全部部门级别，3个人级别
        parameters.put("idList",user.getUserIds());//level为2时 包含部门下所有用户id ,level 为3时 只有当前登录人id
        parameters.put("userId",user.getTid());
        parameters.put("departmentId",user.getOfficeId());//用户部门ID
        vo.setParameters(parameters);

        // 封装分页参数
        Pageable pageable = new Pageable();
        String start = request.getParameter("start");
        String length = request.getParameter("length");

        //封装排序参数
        String order = request.getParameter("order[0][column]");//排序的列号
        String orderDir = request.getParameter("order[0][dir]");//排序的顺序asc or desc
        String orderColumn = request.getParameter("columns["+order+"][data]");//排序的列
        log.info("标题排序参数：排序的列号："+order+"；排序的顺序："+orderDir+";排序的列："+orderColumn);
        Map<String, Object>  sortParameters=new HashMap<String, Object>();
        sortParameters.put("orderColumn", orderColumn);
        sortParameters.put("orderDir", orderDir);
        vo.setSort(sortParameters);

        pageable.setCurrentPage((Integer.parseInt(start)/Integer.parseInt(length)+1));
        log.info("分页参数=>第X页："+(Integer.parseInt(start)/Integer.parseInt(length)+1));
        pageable.setPageSize(Integer.parseInt(length));
        vo.setPageable(pageable);

        return vo;
    }


    /**
     * 处理请求返回结果：封装拉取的数据给表格(dataTable)以便渲染出内容
     *
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static DataTable  resultToDataTable(PageList list) {
        DataTable dt = new DataTable();

        long displayCount = list.size();

        long TotalCount = list.getTotalCount();

        log.info("当前页显示的条数--->displayCount：" + displayCount);

        log.info("条件查询出的条数--->TotalCount：" + TotalCount);

        dt.setAaData(list);

        dt.setiTotalDisplayRecords(TotalCount);

        dt.setiTotalRecords(TotalCount);

        return dt;
    }


    /**
     * 处理时间的转换器，默认格式是yyyy-MM-dd HH:mm:ss可以被重载
     *
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @ExceptionHandler
    @ResponseBody
    public final JsonResult handleException(Exception ex) {

        if (ex instanceof ServiceException) {
            ServiceException be = (ServiceException) ex;
            ex.printStackTrace();
            return JsonResult.createErrorMsg(be.getMessage());
        }
        ex.printStackTrace();
        return JsonResult.createErrorMsg(ex.getMessage());
    }

    public static JsonResult returnSuccess(String msg) {
        return JsonResult.createSuccess(msg);
    }

    public static JsonResult returnSuccess(Object obj, String msg) {
        return JsonResult.createSuccess(obj, msg);
    }

    public static JsonResult returnSuccess() {
        return JsonResult.createSuccess();
    }

    public static JsonResult returnSuccess(Object obj) {
        return JsonResult.createSuccess(obj);
    }
    public static JsonResult createMsg(Object obj, String msg, boolean status) {
        JsonResult jp = new JsonResult();
        jp.setMsg(msg);
        jp.setSuccess(status);
        jp.setResult(obj);
        return jp;
    }

    /**
     * 参数绑定异常
     */
   /* @ExceptionHandler
    public String bindException() {
        return "errors/error";
    }*/

}
